package com.wenjun.young.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.wenjun.young.config.WxMaConfiguration;
import com.wenjun.young.web.dao.intf.WxUserDao;
import com.wenjun.young.web.entity.WxUserEntity;
import com.wenjun.young.web.entity.form.LoginForm;
import com.wenjun.young.web.entity.model.AjaxResult;
import com.wenjun.young.web.service.AppService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private WxUserDao wxUserDao;

    @Override
    @Transactional
    public AjaxResult login(LoginForm form) {
        final WxMaService wxService = WxMaConfiguration.getMaService(form.getAppId());
        try {
            // 根据用户的code和小程序的appid获取该用户对应小程序的唯一openid
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(form.getCode());
            WxUserEntity wxUser = wxUserDao.selectUserByOpenId(session.getOpenid());
            if (wxUser == null) {
                // 创建用户
                wxUser = new WxUserEntity();
                // 类型 1医生2管理
                wxUser.setType("1");
                // 授权 默认未授权
                wxUser.setIsAuth(false);
            }
            wxUser.setOpenid(session.getOpenid());
            wxUser.setSessionKey(session.getSessionKey());
            wxUser.setNickName(form.getNickName());
            wxUser.setAvatarUrl(form.getAvatarUrl());
            wxUser.setMobile(form.getMobile());
            wxUser.setGender(form.getGender());
            wxUser.setCountry(form.getCountry());
            wxUser.setProvince(form.getProvince());
            wxUser.setCity(form.getCity());
            wxUser.setLanguage(form.getLanguage());
            if (wxUser.getId() != null) {
                wxUserDao.updateById(wxUser);
            } else {
                wxUserDao.save(wxUser);
            }
            return AjaxResult.success(wxUser);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error("授权失败!");
        }
    }

}
